/*
 *  hackds/course_design/polynomial/main.c
 *
 *  (C) 2011 Harry Wei
 */

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <error.h>

#include "./include/pm.h"

int 
main(int argc, char *argv[])
{
	int i = 0;
	int counter = 0;
	int temp = 0;
	int mul_counter = 0;
	int flag = 0;
	char ch;
	char *exp = NULL;
	struct poly **store = NULL;
	struct poly *print = NULL;

	exp = (char *)malloc(sizeof(char) * BUF);
	if (!exp) {
		fprintf(stderr, "Allocate Error!\n");
		return 0;
	}
	fprintf(stdout, "What about your polynomial: ");
	fscanf(stdin, "%s", exp);
	if (check(exp))
		return 1;
	i = 0;
	while (exp[i]) {
		if ((0 == flag) && 
			('a' <= exp[i] && 'z' >= exp[i]) ||
				('A' <= exp[i] && 'Z' >= exp[i])) {
			ch = exp[i];
			flag = 1;
			i += 1;
			continue;
		}
		if ('*' == exp[i]) {
			mul_counter += 1;
			i += 1;
		} else {
			i += 1;
			continue;
		}
	}
	store = (struct poly **)malloc(sizeof(struct poly *) * (mul_counter + 1));
	if (!store) {
		fprintf(stderr, "Allocate Error!\n");
		return 1;
	}
	for (i = 0; i < mul_counter + 1; i++) {
		store[i] = (struct poly *)malloc(sizeof(struct poly));
		if (!store[i]) {
			fprintf(stderr, "Allocate Error!\n");
			return 1;
		}
	}
	if (allocate(store, exp, mul_counter, ch))
		return 1;
	if (sort(store, mul_counter))
		return 1;
#if DEBUG == 1
	for (i = 0; i < mul_counter + 1; i++) {
		print = store[i]->next;
		while (print) {
			printf("i %d: %c %c\n", i, print->multiple, print->power);
			print = print->next;
		}
	}
#endif
	if (multiple(store, mul_counter))
		return 1;
	i = 0;
	while (store[0][i].next) {
		printf("last: %d %d\n", store[0][i].multiple, store[0][i].power);
		i += 1;
	}
	return 0;
}
